<template>
  <el-dialog
    title="修改密码"
    :append-to-body="true"
    :visible="dialogVisible"
    @close="$emit('close')"
    custom-class="custom-dialog"
  >
    <el-form>
      <el-form-item>
        <el-input
          placeholder="输入新密码"
          v-model="pw1"
          show-password
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-input
          placeholder="再输入一次"
          v-model="pw2"
          show-password
        ></el-input>
      </el-form-item>
    </el-form>
    <el-alert v-show="err.length > 0" type="error" :closable="false">
      <div v-for="(e, i) in err" :key="i">{{ e }}</div>
    </el-alert>
    <div style="text-align: right; margin-top: 12px">
      <el-button v-show="available" type="primary" @click="update()"
        >提交</el-button
      >
      <el-button type="text" @click="$emit('close')">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: "passwdEditor",
  props: {
    dialogVisible: {
      type: Boolean,
      required: true,
    },
    pw0: {
      type: String,
      required: false,
    },
  },
  components: {},
  data() {
    return {
      pw1: "",
      pw2: "",
      err: [],
    };
  },
  computed: {
    dialogWidth() {
      if (this.viewSize.width < 500) return "90%";
      return (500 / this.viewSize.width) * 100 + "%";
    },
    viewSize() {
      return this.$store.state.viewSize;
    },
    available() {
      if (this.pw1.length == 0 || this.pw2.length == 0) return false;
      return true;
    },
  },
  methods: {
    check() {
      this.err = [];
      if (this.pw1 != this.pw2) {
        this.err.push("两次输入的密码不一致");
      }
      if (this.pw1.length < 6) {
        this.err.push("密码长度至少6位");
      }
      if (this.pw1 == this.pw0) {
        this.err.push("输入的密码和原密码一样");
      }
    },
    update() {
      this.check();
      if (this.err.length == 0) {
        this.$store.commit("setLoading", true);
        this.axios
          .post("api/", {
            action: "modify_passwd",
            payload: {
              login_data: this.$store.state.loginData,
              passwd_new: this.pw1,
            },
          })
          .then((response) => {
            window.console.log(response.data);
            this.$store.commit("setLoginData", {
              number: this.$store.state.loginData.number,
              passwd: this.pw1,
            });
            this.$store.commit("setLoading", false);
            this.$emit("close");
          });
      }
    },
  },
};
</script>

<style scoped>
.alert {
  padding: 0.4em 1em;
}
.title {
  font-size: 2em;
  padding-bottom: 0.25em;
}
</style>